<template>
  <t-dialog
    v-model:visible="show"
    :width="900"
    :header="plugin.t('reverse.pull.title')"
    destroyOnClose
    :closeOnOverlayClick="false"
  >
    <template #body>
      <div class="plugin-miravia-reverse-pull">
        <t-alert class="alert" theme="info">
          <span v-for="alert in plugin.tm('reverse.pull.alert')">{{ alert }}</span>
        </t-alert>
        <t-form label-align="left">
          <t-form-item :label="plugin.t('reverse.pull.time')">
            <t-date-picker 
              v-model="form.time" 
              :format="app.time.formatTime()" 
              valueType="Date"
              enable-time-picker
            />
          </t-form-item>
        </t-form>
      </div>
    </template>
    <template #footer>
      <t-button theme="primary" v-if="!loading" @click="onSubmit">
        {{ plugin.t('reverse.pull.button') }}
      </t-button>
      <t-progress theme="plump" :percentage="progress" status="active" v-else />
    </template>
  </t-dialog>
</template>
<script setup>
  import { ref, reactive } from 'vue'
  import app from '@/app'
  import index from '../../index'
  import { pull, post } from '@/api/provider/miravia_reverse'
  import reverseStore from '../../store/reverse'

  const plugin = index.plugin

  const show = ref(false)
  const loading = ref(false)
  const progress = ref(0)
  const form = reactive({
    time: new Date,
  })

  const open = () => {
    show.value = true
    const list = reverseStore.getList()
    if(list.length > 0) {
      form.time = list[0].time.toDate()
    }
  }

  const onSubmit = async () => {
    loading.value = true
    
    try{
      await onPull(app.time.load(form.time).unix())
      app.message('success', plugin.message('reverse.pull.message.ok'))
    } catch(e) {
      console.error(e)
      app.message('warning', plugin.message('reverse.pull.message.error'))
    }

    await reverseStore.reset(1)
    loading.value = false
  }

  // 拉取订单
  const onPull = async (time) => {
    const data = {
      time,
      page: 1,
      page_size: 50,
      count: 0,
      status: ['REFUND_SUCCESS']
    }
    while(true) {
      const orders = await pull(data)
      const items = await reverseStore.item(orders.items)
      const total = Math.max(orders.total, data.count)
      // 循环订单
      for (const order of orders.items) {
        await onCreate(order, items)
        data.count++
        progress.value = parseInt(data.count / total * 100)
      }
      
      if(data.count >= total) return
      // 分页++
      data.page++
    }
  }

  // 创建订单
  const onCreate = async (order, items) => {
    for (const line of order.reverse_order_lines) {
      const item = items[line.trade_order_line_id]
      await post({
        line_id: line.reverse_order_line_id,
        number: order.reverse_order_id,
        order_number: order.trade_order_id,
        name: item.name,
        image: item.product_main_image,
        money: app.math.div(line.refund_amount, 100),
        sku: line.seller_sku_id,
        time: line.return_order_line_gmt_create
      })
    }
  }

  defineExpose({ open })
</script>
<style lang="scss">
  @import '@/style/global';

  .plugin-miravia-reverse-pull{
    overflow: hidden;

    .alert{
      margin-bottom: 25px;
      span{
        display: block;
        line-height: 25px;
      }
    }
  }
</style>